package com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap;

import com.alibaba.cirtus.ots.application.adapter.ability.model.response.WarehouseResponse;
import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.AllocateOrderDetailSDO;
import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.AllocateOrderWithOrderDetailsSDOV2;
import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.WmsSDO;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.RequestUtils;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.citrus.ots.common.util.JsonUtil;
import com.alibaba.citrus.ots.common.util.NameUtil;
import com.alibaba.citrus.ots.common.util.TimeUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.bcorder.model.dto.QueryCargoZoneByIdRequest;
import com.epoch.app.bcorder.model.dto.QueryCargoZoneByIdResponse;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.crunifiedinventory.sdo.AllocateOrderSDO;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapIf012Detail;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapIf012Request;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapIf012SDO;
import com.epoch.app.otsapplicationadaptersdk.sapv2.mnsapif012v2.dto.DoHandlerRequest;
import com.epoch.app.otsapplicationadaptersdk.sapv2.mnsapif012v2.service.MnSapIf012V2Service;
import com.epoch.app.otsapplicationadaptersdk.service.ApiAdapterService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author zhoubc
 * @description: 平台请求sap销售订单创建 ,调拔订单下发SAP接口（类型20）
 * @date 2021/9/28 21:24
 */
@Component
@Primary
public class MnSapIf012V2ServiceImpl implements MnSapIf012V2Service {
    private final Log log = Log.getLogger(MnSapIf012V2ServiceImpl.class);

    @Resource
    private UnifiedInventoryService unifiedInventoryService;
    @Resource
    private ApiAdapterService apiAdapterService;

    private static final String error = "---yhw---";

    @Override
    @ProcessInvoker(remark = "MnSapIf012V2Service", errorCode = "OTS-02-007-00-16-999", printLog = true)
    public Object doHandler(DoHandlerRequest doHandlerRequest) {
        log.info("MnSapIf012ServiceImpl doHandler request:{}",JSON.toJSONString(doHandlerRequest));
        MnSapIf012Request request = new MnSapIf012Request();
        request.setMessageHeader(RequestUtils.generateMessageHeader("MnSapIf012","ECC"));
        MnSapIf012SDO sdo = new MnSapIf012SDO();

        AllocateOrderWithOrderDetailsSDOV2 withOrderDetailsSDO = JSON.parseObject(doHandlerRequest.getMessage(),
                AllocateOrderWithOrderDetailsSDOV2.class);
        if (withOrderDetailsSDO == null){
            log.error(error+ "消息体数据为空");
            return null;
        }
        AllocateOrderSDO allocateOrderSDO = withOrderDetailsSDO.getAllocateOrderSDO();
        if (allocateOrderSDO == null)return null;

        sdo.setAllocateOrderId(allocateOrderSDO.getCode());
        if (Objects.equals(allocateOrderSDO.getReturnOrder(),Boolean.TRUE)){
            sdo.setOrderType("ZRE");
        }else {
            sdo.setOrderType("ZOR");
        }

        sdo.setSaleOrganizationCode(allocateOrderSDO.getSapSalesOrgId());
        sdo.setSapChannel(allocateOrderSDO.getSapChannel()==null?"20":allocateOrderSDO.getSapChannel() +"");
//        sdo.setProductGroupCode(allocateOrderSDO.getProductGroup());
        sdo.setProductGroupCode("11");//货品组先固定下 11
        //创建人转一下json
        sdo.setOutCreator(NameUtil.getRealName(allocateOrderSDO.getCreator()));
        sdo.setOutCreateDate(TimeUtil.formatYYYY_MM_dd_time(allocateOrderSDO.getGmt_create()));
        sdo.setDocTime(TimeUtil.formatYYYY_MM_dd(allocateOrderSDO.getDocDate()));

        //TODO 售达方 仓库档案上的
        WmsSDO shipWmsSDO = getWmsSDO(allocateOrderSDO.getShipAreaId());
        WmsSDO receiveWmsSDO = getWmsSDO(allocateOrderSDO.getReceiveAreaId());


//        SAPArea ship = new SAPArea();
//        ship.setCargoZoneIdList(Lists.newArrayList(withOrderDetailsSDO.getShipAreaId()));
//        QueryCargoZoneByIdResponse queryCargoZoneByIdResponse = this.doHandler$callAPI2(ship);
//        Map shipMap = null;
//        WarehouseResponse shipArea = getWareHouse(shipMap);
//
//        SAPArea receive = new SAPArea();
//        receive.setCargoZoneIdList(Lists.newArrayList(withOrderDetailsSDO.getReceiveAreaId()));
//        queryCargoZoneByIdResponse = this.doHandler$callAPI2(receive);
//        //TODO 仓库查询
//        Map receiveMap = null;
//        WarehouseResponse receiveArea = getWareHouse(receiveMap);

        //deliveryIntoryCode 是发货的

        sdo.setSoldPartCode(receiveWmsSDO.getSapSalesBPCode());
        sdo.setDeliveryPartCode(receiveWmsSDO.getSapDeliveryBPCode());

        sdo.setDeliveryFactoryCode(shipWmsSDO.getFactoryCode());
        sdo.setDeliveryInventoryCode("DEFAULT".equals(shipWmsSDO.getInventoryCode())?null:shipWmsSDO.getInventoryCode());
        sdo.setExpectedDeliveryTime(TimeUtil.formatYYYY_MM_dd(allocateOrderSDO.getExpectedDeliveryDate()));
        sdo.setShipType(allocateOrderSDO.getShipMethod() == null? null:String.valueOf("0" +allocateOrderSDO.getShipMethod()));
        sdo.setRemark(allocateOrderSDO.getRemark());
        sdo.setCostCenter(allocateOrderSDO.getSapCostCenter());
        //退单才传递订单原因
        if (Objects.equals(Boolean.TRUE,allocateOrderSDO.getReturnOrder())){
            sdo.setOrderReason(allocateOrderSDO.getOrderReason());
        }
//        sdo.setOrderReason(allocateOrderSDO.getOrderReason());
        sdo.setFeatures(allocateOrderSDO.getFeatures());

        List<MnSapIf012Detail> details = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(withOrderDetailsSDO.getAllocateOrderDetailSDOS())){
            for (AllocateOrderDetailSDO detailSDO : withOrderDetailsSDO.getAllocateOrderDetailSDOS()){
                MnSapIf012Detail detail = new MnSapIf012Detail();
                detail.setAllocateOrderLineId(detailSDO.getLineNo());
//                detail.setScItemId(SapAndCrmFieldDealUtils.generateIdField(detailSDO.getScItemCode()));
                detail.setScItemId(subStringScItmCode(detailSDO.getScItemCode()));
                detail.setQuantity(detailSDO.getQuantity());
                detail.setUnit(detailSDO.getUnit());
                detail.setProduceDate(TimeUtil.formatYYYY_MM_dd(detailSDO.getExpectedProduceDate()));
                //退货需要发票号和行号
                detail.setInvoiceNo(detailSDO.getInvoiceNo());
                detail.setInvoiceLineNo(detailSDO.getInvoiceLineNo());
                detail.setDeliveryDate(TimeUtil.formatYYYY_MM_dd(allocateOrderSDO.getExpectedDeliveryDate()));
                detail.setRemarks(detailSDO.getRemarks());
                detail.setFeatures(detailSDO.getFeatures());
                details.add(detail);
            }
        }
        sdo.setItems(details);

        request.setData(Lists.newArrayList(sdo));

        return apiAdapterService.reqSapSalesOrderCreate(request);
    }

    public  WmsSDO getWmsSDO(String areaId){
        if (StringUtils.isNotBlank(areaId)){
            QueryCargoZoneByIdRequest queryCargoZoneByIdRequest = new QueryCargoZoneByIdRequest();
            queryCargoZoneByIdRequest.setCargoZoneIdList(Lists.newArrayList(areaId));
            QueryCargoZoneByIdResponse shipAreaQuery = unifiedInventoryService.queryCargoZoneById(queryCargoZoneByIdRequest);
            return getWmsSDO(shipAreaQuery);
        }
        return new WmsSDO();
    }

    public static WmsSDO getWmsSDO(QueryCargoZoneByIdResponse response){
        WmsSDO wmsSDO = new WmsSDO();
        if (response !=null && CollectionUtils.isNotEmpty(response.getResult())){
            JSONArray array = JSON.parseArray(JSON.toJSONString(response.getResult()));
            if (array != null && array.size() > 0){
                JSONObject data = array.getJSONObject(0);
//                wmsSDO.setInventoryCode(data.getString("code"));
                wmsSDO.setInventoryCode(data.getString("warehouseCode"));
                wmsSDO.setFactoryCode(data.getString("sapFactoryCode"));
                wmsSDO.setSapCompanyCode(data.getString("sapCompanyCode"));
                wmsSDO.setSapSalesBPCode(data.getString("sapSaleBPCode"));//这个得依靠仓库返回的字段没有s
                wmsSDO.setSapDeliveryBPCode(data.getString("sapDeliveryBPCode"));
                wmsSDO.setSapInternalSalesBPCode(data.getString("sapInternalSalesBPCode"));
                wmsSDO.setSapInternalDeliveryBPCode(data.getString("sapInternalDeliveryBPCode"));

//                if (StringUtils.isNotBlank(data.getString("features"))){
//                    JSONObject features = JSON.parseObject(data.getString("features"));
//                    if (features != null){
//                        wmsSDO.setSapCompanyCode(features.getString(""));
//                    }
//                }
            }
        }
        return wmsSDO;
    }

    public static WarehouseResponse getWareHouse(Map map){
        JSONObject obj = JSON.parseObject(JSONObject.toJSONString(map));
        if (obj != null){
            JSONArray array = obj.getJSONArray("result");
            if (array != null && array.size() > 0){
                obj = array.getJSONObject(0);
                WarehouseResponse r = JsonUtil.convert(obj,WarehouseResponse.class);
                return r;
            }
        }
        return null;
    }

    /**
     * 截取scItemCode 固定长度为12
     * @param str
     * @return
     */
    public static String subStringScItmCode(String str){
        if (StringUtils.isBlank(str)){
            return null;
        }
        if (str.length()>12){
            return str.substring(str.length()-12);
        }
        return str;
    }

}
